from django.shortcuts import render
from rest_framework.permissions import BasePermission
from rest_framework.viewsets import ModelViewSet
from users.ser import *


# /user/1/
class UserPermission(BasePermission):
    # 用户可以查单个数据,  必须是和自己id相同的数据
    def has_permission(self, request, view):
        print(request)
        user = request.user
        if user.is_superuser:
            return True
        if view.action in ['retrieve', 'update']:  # retrieve,  update,  不能 destory
            pk = int(view.kwargs.get('pk'))
            if pk == user.id:
                return True
            else:
                return False
        return False

        # user.id => 1    /user/2/

        # 用户访问的数据是自己的数据, 才能有权限


class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSer

    permission_classes = (UserPermission,)
